package com.cqeec.gams.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.cqeec.gams.entity.Account;
import com.cqeec.gams.entity.FunctionalModule;
import com.cqeec.gams.service.AccountService;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;

@Controller
public class LoginController {
	@Autowired
	private DefaultKaptcha captchaProducer;
	@Autowired
	private AccountService accountService;

	@RequestMapping("/user/exit.html")
	public String exit(HttpSession session) {
		session.removeAttribute("account");
		return "redirect:/login.html";
	}

	@RequestMapping("/user/login.html")
	public ModelAndView login(String user, String password, String captch, HttpSession session) {
		ModelAndView mav = new ModelAndView();
		// 获取系统生成的验证码（在当前会话对象里）
		Object code = session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
		if (code == null) {
			mav.setViewName("login"); // 如果验证码失效了则需重新登录
		} else {
			String strCode = (String) code;
			if (strCode.equals(captch)) {
				Account account = accountService.login(user, password);
				if (account == null) {
					mav.setViewName("login"); // 设置跳转到的页面名称
					mav.addObject("message", "用户名或密码错误！"); // 添加数据带回页面 相当于Servlet中的request.setAttribute("属性名",值);
				} else {
					// 登录成功
					// 将登录的账户信息保存到会话
					session.setAttribute("account", account);
					// 根据用户ID获取用户角色所拥有的功能模块代码
					List<FunctionalModule> list = accountService.getUserFunctionalModule(account.getId());
					List<String> userPermission = new ArrayList<String>();
					for (FunctionalModule fm : list) {
						userPermission.add(fm.getCode());
					}
					session.setAttribute("userPermission", userPermission);
					// 重定向到主页
					mav.setViewName("redirect:/main.html");
				}
			} else {
				mav.setViewName("login");
				mav.addObject("message", "验证码错误！");
			}
		}
		return mav;
	}

	@RequestMapping({ "/", "/login.html" })
	public String gotoLoginPage() {
		return "login";
	}

	@RequestMapping("/captcha.html")
	public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setDateHeader("Expires", 0);
		// Set standard HTTP/1.1 no-cache headers.
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		// Set standard HTTP/1.0 no-cache header.
		response.setHeader("Pragma", "no-cache");
		// return a jpeg
		response.setContentType("image/jpeg");
		// create the text for the image
		String capText = captchaProducer.createText();
		// store the text in the session
		request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
		// create the image with the text
		BufferedImage bi = captchaProducer.createImage(capText);
		ServletOutputStream out = response.getOutputStream();
		// write the data out
		ImageIO.write(bi, "jpg", out);
		try {
			out.flush();
		} finally {
			out.close();
		}
	}
}
